% function [fac,lam]=extract(data) extracts first principal component from
% t*n matrix data, loadings are normalized so that lam'lam/n=I, fac is tx1,
% lam is nx1
function varargout=extract(data)
[t,n]=size(data);
xx=data'*data;
[evec,eval]=eig(xx);

% sorting evec so that they correspond to eval in descending order
[eval,index]=sort(diag(eval));
index=flipud(index); 		   % to get descending order
evc=zeros(n,n);
for i=1:n
   evc(:,i)=evec(:,index(i));
end

lam = sqrt(n)*evc(:,1);
fac=data*lam/n;

varargout(1) = {fac};
varargout(2) = {lam}; 